﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SQLite;

namespace Crawler_v1.utils
{
    class MySqliteHelper
    {
        //数据库连接字符串(web.config来配置)，可以动态更改SQLString支持多数据库.        
        public static string connectionString = "Data Source=" + Application.StartupPath + "/zouchuqu.db";

        private volatile static SQLiteConnection coon = null;

        private static readonly object lockHelper = new object();

        /// <summary>
        /// 获得连接
        /// </summary>
        /// <returns></returns>
        public static SQLiteConnection getConnection()
        {
            if (coon == null)
            {
                lock (lockHelper)
                {
                    if (coon == null)
                    {
                        coon = new SQLiteConnection(connectionString);
                        coon.Open();
                    }
                }
            }
            return coon;
        }

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString)
        {
            SQLiteConnection connection = getConnection();
            using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
            {
                try
                {
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.SQLite.SQLiteException E)
                {
                    connection.Close();
                    throw new Exception(E.Message);
                }
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public static object GetSingle(string SQLString)
        {
            SQLiteConnection connection = getConnection();

            using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
            {
                try
                {
                    object obj = cmd.ExecuteScalar();
                    if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    {
                        return null;
                    }
                    else
                    {
                        return obj;
                    }
                }
                catch (System.Data.SQLite.SQLiteException e)
                {
                    connection.Close();
                    throw new Exception(e.Message);
                }
            }

        }

    }
}
